package com.leesche.zcsp.node.utils.web.filemanager;

import com.leesche.zcsp.node.app.v1.controller.individual.AppIndivdualController;
import com.leesche.zcsp.node.utils.web.WebUtils;
import com.leesche.zcsp.node.utils.web.gernerator.UUIDGenerateUtil;
import com.leesche.zcsp.node.web.constants.Constants;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.terracotta.statistics.Statistic;

import java.io.File;
import java.io.IOException;

public class FileManager {

    private static final Logger logger = Logger
            .getLogger(FileManager.class);

    public static String  ERRORSTR =  "ERROR:";

    /**
     * @return 已保存的图片web url 地址
     * @Title: saveImage(MultipartFile file, String savePath)
     * @Description: TODO(保存图片至服务器指定位置)
     * @author Jerry Chan
     * @date 2016/12/19 18:11
     */
    public static String saveImage(MultipartFile file, String savePath) {
        if (file.isEmpty()) {
            //return WebResult.failure("请选择Logo图片").toMap();
            return ERRORSTR+"请选择需上传的图片";
        }

        String fileName = file.getOriginalFilename();
        String extName = fileName.substring(fileName.lastIndexOf("."));

        try {

            if (!WebUtils.checkIsImage(extName)
                    && !file.getContentType().matches("image.*")) {
                //return WebResult.failure("上传的文件必须是图片").toMap();
                return ERRORSTR+"上传的文件必须是图片";
            }

            String hexString = WebUtils.getFileHexString(file.getInputStream());

            boolean flag = false;
            String[] magic = Constants.SYSTEM_IMAGE_MAGICNUMBER;
            for (int i = 0; i < magic.length; i++) {
                if (magic[i].equals(hexString)) {
                    flag = true;
                    break;
                }
            }

            if (flag == false) {
                //return WebResult.failure("上传的文件类型不是图片").toMap();
                return ERRORSTR+"上传的文件类型不是图片";
            }

        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            //return WebResult.failure("上传的Logo无法识别").toMap();
            return ERRORSTR+"上传的图片无法识别";
        }

        if (file.getSize() > Constants.SYSTEM_IMAGE_SIZE) {

            return ERRORSTR+"上传的图片太大，不能超过" + (Constants.SYSTEM_IMAGE_SIZE / (1024 * 1000)) + "M";
        }

        //String logopath = SessionManager.getContext().getRealPath("").replace(Constants.SITE_NAME, savePath);

        String logoname = UUIDGenerateUtil.generateUUID() + extName;

        File logofile = new File(savePath, logoname);

        if (!logofile.exists()) {
            logofile.mkdirs();
        }

        try {
            file.transferTo(logofile);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            return Constants.SYSTEM_ERROR_PROMPT_MSG;
        }

        //return SessionManager.getWebServerURL() + savePath + "/" + logoname;
        return logoname;
    }


}
